import * as step from '@flow-step/step-toolkit'
import {RosInterface} from './ros'
import {CreateStackRequest, CreateStackRequestParameters, CreateStackResponse} from '@alicloud/ros20190910'
import {IParams} from './params'
import {getParameters} from './getParameters'
import {getTemplateBody} from './getTemplate'
import {isNotEmpty} from './util'


export async function createStack(params: IParams, ros: RosInterface) {
    let createStackParams: any = new CreateStackRequest()
    const parameters = getParameters()
    const templateBody = getTemplateBody()
    let stackParameters: any[] = []
    createStackParams['regionId'] = params.REGION_ID
    createStackParams['stackName'] = params.STACK_NAME
    createStackParams['templateBody'] = templateBody
    if (isNotEmpty(params.TIMEOUT_MINUTES) && params.TIMEOUT_MINUTES !== 0) {
        createStackParams['timeoutInMinutes'] = params.TIMEOUT_MINUTES
    }
    else {
        createStackParams['timeoutInMinutes'] = 60
    }
    if (isNotEmpty(params.RAM_ROLE_NAME)) {
        createStackParams['ramRoleName'] = params.RAM_ROLE_NAME
    }
    else {
        createStackParams['ramRoleName'] = 'AliyunROSFullRole'
    }
    if (parameters) {
        for (let [paramKey, paramValue] of parameters) {
            stackParameters.push(new CreateStackRequestParameters({
                parameterKey: paramKey,
                parameterValue: paramValue
            }))
        }
        step.info(`CreateStack params is ${JSON.stringify(stackParameters, null, 2)}`);
        createStackParams['parameters'] = stackParameters
    }
    const request: CreateStackRequest = new CreateStackRequest(createStackParams)
    let response: CreateStackResponse
    step.info(`CreateStack request is ${JSON.stringify(createStackParams, null, 2)}`);
    try {
        response = await ros.createStack(request)
    } catch (error: any) {
        step.error(`Failed to CreateStack. Code: ${error?.code}, Message: ${error.data?.Message}, RequestId: ${error.data?.RequestId}`);
        if (!isNotEmpty(error.data?.Message)) {
            step.error(`Unexpected CreateStack error. Error: ${JSON.stringify(error, null, 2)}`);
        }
        return false
    }
    const StackId = response.body?.stackId

    if (isNotEmpty(StackId)) {
        return StackId
    } else {
        return false
    }
}